// src/stores/platform.ts
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { authAPI } from '@/api/platform'

// 定义用户类型
interface User {
  id: number
  username: string
  email: string
  role: string
  avatar?: string
}

// 定义通知类型
interface Notification {
  id: number
  title: string
  content: string
  type: 'info' | 'success' | 'warning' | 'error'
  time: string
  read: boolean
}

export const usePlatformStore = defineStore('platform', () => {
  // 响应式状态
  const user = ref<User | null>(null)
  const isAuthenticated = ref(false)
  const loading = ref(false)
  const notifications = ref<Notification[]>([])
  const sidebarCollapsed = ref(false)
  
  // 租户数据
  const tenants = reactive({
    list: [] as any[],
    total: 0,
    loading: false
  })
  
  // 财务数据
  const finance = reactive({
    income: 0,
    expenses: 0,
    profit: 0
  })
  
  // 系统状态
  const systemStatus = reactive({
    cpu: 0,
    memory: 0,
    disk: 0,
    status: 'normal' as 'normal' | 'warning' | 'error'
  })
  
  // 方法
  const login = async (credentials: { username: string; password: string }) => {
    loading.value = true
    try {
      const response = await authAPI.login(credentials)
      const { token, user: userData } = response.data
      
      // 保存token
      localStorage.setItem('platform_admin_token', token)
      
      // 设置用户信息
      user.value = userData
      isAuthenticated.value = true
      
      return { success: true, data: response.data }
    } catch (error) {
      return { success: false, error }
    } finally {
      loading.value = false
    }
  }
  
  const logout = async () => {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      // 清除本地状态
      localStorage.removeItem('platform_admin_token')
      user.value = null
      isAuthenticated.value = false
    }
  }
  
  const getCurrentUser = async () => {
    try {
      const response = await authAPI.getCurrentUser()
      user.value = response.data
      isAuthenticated.value = true
      return response.data
    } catch (error) {
      // 如果获取当前用户失败，清除认证状态
      localStorage.removeItem('platform_admin_token')
      user.value = null
      isAuthenticated.value = false
      throw error
    }
  }
  
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  const addNotification = (notification: Omit<Notification, 'id' | 'time' | 'read'>) => {
    const newNotification: Notification = {
      id: Date.now(),
      time: new Date().toLocaleString(),
      read: false,
      ...notification
    }
    notifications.value.unshift(newNotification)
  }
  
  const markNotificationAsRead = (id: number) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }
  
  const markAllNotificationsAsRead = () => {
    notifications.value.forEach(n => {
      n.read = true
    })
  }
  
  const removeNotification = (id: number) => {
    notifications.value = notifications.value.filter(n => n.id !== id)
  }
  
  const clearAllNotifications = () => {
    notifications.value = []
  }
  
  // 初始化store
  const initialize = async () => {
    const token = localStorage.getItem('platform_admin_token')
    if (token) {
      try {
        await getCurrentUser()
      } catch (error) {
        console.error('初始化用户信息失败:', error)
      }
    }
  }
  
  return {
    // 状态
    user,
    isAuthenticated,
    loading,
    notifications,
    sidebarCollapsed,
    tenants,
    finance,
    systemStatus,
    
    // 方法
    login,
    logout,
    getCurrentUser,
    toggleSidebar,
    addNotification,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    removeNotification,
    clearAllNotifications,
    initialize
  }
})